#coding=utf-8
import datetime
import os
import time

from loguru import logger
from playwright.sync_api import sync_playwright
import traceback

import jingdong.jd_common as jd_common

def group_by_period(job_list):
    job_group = {}
    period_list = list(set(map(lambda x: x['period'], job_list)))
    for period in period_list:
        filter_list = list(filter(lambda x: x['period'] == period, job_list))
        job_group[period] = filter_list
    return job_group

def jd_main(host, account_list):
    try:
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
        store_id_list = list(set(map(lambda x: x['storeId'], account_list)))
        logger.info('正在运行京东RPA...')
        with sync_playwright() as playwright:
            jd_func = jd_common.JD_BILL(playwright, host, 'haiwangou-key')
            for store_id in store_id_list:
                store_job_list = list(filter(lambda x: x['storeId'] == store_id, account_list))
                # 检查并登录
                jd_func.login(store_job_list[0])
                # 按照周期分组，按每个周期循环运行，每跑完一个周期上传一次
                job_group = group_by_period(store_job_list)
                for period, job_list in job_group.items():
                    param_list = []
                    file_list = []
                    logger.info(f"正在下载【{job_list[0]['platformStoreName']}】账单")
                    for item in job_list:
                        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        if item['accountType'] == '结算单':
                            logger.info('开始下载结算单...')
                            bill_file, success = jd_func.download_bill_file(item, period)
                            has_account = success is not None
                            # 店铺标识不正确
                            if success == 0:
                                message = f'按照店铺标识【{item["account"]}】找不到账户'
                                logger.info(message)
                                log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                                jd_func.update_log(log_id_list, message)
                                break
                                # 下载上两个月的结算单
                            last_two_month = (datetime.datetime.strptime(period + '-01', '%Y-%m-%d') - datetime.timedelta(days=1)).strftime('%Y-%m')
                            last_tow_month_bill_file, success = jd_func.download_bill_file(item, last_two_month)
                            if bill_file is not None:
                                file_list.append(bill_file)
                                dir_path, file_name = os.path.split(bill_file)
                                if last_tow_month_bill_file is not None:
                                    file_list.append(last_tow_month_bill_file)
                                    dir_path, file_name2 = os.path.split(last_tow_month_bill_file)
                                    param_list.append({'orderType': '结算单', 'fileName': file_name + ',' + file_name2, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                else:
                                    param_list.append({'orderType': '结算单', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            else:
                                param_list.append({'orderType': '结算单', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})

                        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        if item['accountType'] == '资金流水':
                            logger.info('开始下载资金流水...')
                            bill_file, success = jd_func.download_fund_flow(item, period)
                            has_account = success is not None
                            # 店铺标识不正确
                            if success == 0:
                                message = f'按照店铺标识【{item["account"]}】找不到账户'
                                logger.info(message)
                                log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                                jd_func.update_log(log_id_list, message)
                                break
                            if bill_file is not None:
                                file_list.append(bill_file)
                                dir_path, file_name = os.path.split(bill_file)
                                param_list.append({'orderType': '资金流水', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            else:
                                param_list.append({'orderType': '资金流水', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '结算单总数':
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_count = jd_func.get_bill_count(item, period)
                            has_account = bill_count is not None
                            # 店铺标识不正确
                            if success == 0:
                                message = f'按照店铺标识【{item["account"]}】找不到账户'
                                logger.info(message)
                                log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                                jd_func.update_log(log_id_list, message)
                                break
                            param_list.append({'orderType': '结算单总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '资金流水总数':
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_count = jd_func.get_fund_flow_count(item, period)
                            has_account = bill_count is not None
                            # 店铺标识不正确
                            if success == 0:
                                message = f'按照店铺标识【{item["account"]}】找不到账户'
                                logger.info(message)
                                log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                                jd_func.update_log(log_id_list, message)
                                break
                            param_list.append({'orderType': '资金流水总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                    if not has_account:
                        break
                    if len(param_list) > 0:
                        # 编码字符串
                        coding_param = jd_func.encode_param(param_list)
                        # 上传文件
                        uri = "api/v1/jdBill/jdBillRPAImport/{}".format(item['storeCode'])
                        jd_func.upload_file(uri, coding_param, file_list)
                jd_func.close()
    except:
        logger.info(traceback.format_exc())

